<?php
declare(strict_types=1);

namespace app\model;

use think\Model;

class DistributionRecord extends Model
{
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    // 状态常量
    const STATUS_PENDING = 0;    // 待结算
    const STATUS_SETTLED = 1;    // 已结算
    const STATUS_INVALID = 2;    // 已失效

    /**
     * 创建分销记录
     * @param array $data
     * @return bool
     */
    public static function createRecord(array $data): bool
    {
        try {
            self::create([
                'merchant_id' => $data['merchant_id'],
                'order_id' => $data['order_id'],
                'order_no' => $data['order_no'],
                'user_id' => $data['user_id'],
                'level' => $data['level'],
                'commission' => $data['commission'],
                'status' => self::STATUS_PENDING
            ]);
            return true;
        } catch (\Exception $e) {
            \think\facade\Log::error('创建分销记录失败: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * 获取用户分销统计
     * @param int $userId
     * @param int $merchantId
     * @return array
     */
    public static function getUserStats(int $userId, int $merchantId): array
    {
        $stats = [
            'total_commission' => 0,        // 总佣金
            'pending_commission' => 0,      // 待结算佣金
            'settled_commission' => 0,      // 已结算佣金
            'total_orders' => 0,            // 总订单数
            'level1_commission' => 0,       // 一级佣金
            'level2_commission' => 0,       // 二级佣金
            'today_commission' => 0,        // 今日佣金
            'this_month_commission' => 0    // 本月佣金
        ];

        // 基础统计
        $records = self::where([
            'merchant_id' => $merchantId,
            'user_id' => $userId
        ])->select();

        foreach ($records as $record) {
            $stats['total_commission'] += $record->commission;
            $stats['total_orders']++;

            if ($record->status == self::STATUS_PENDING) {
                $stats['pending_commission'] += $record->commission;
            } elseif ($record->status == self::STATUS_SETTLED) {
                $stats['settled_commission'] += $record->commission;
            }

            if ($record->level == 1) {
                $stats['level1_commission'] += $record->commission;
            } else {
                $stats['level2_commission'] += $record->commission;
            }
        }

        // 今日佣金
        $stats['today_commission'] = self::where([
            'merchant_id' => $merchantId,
            'user_id' => $userId,
        ])->whereTime('create_time', 'today')
          ->sum('commission');

        // 本月佣金
        $stats['this_month_commission'] = self::where([
            'merchant_id' => $merchantId,
            'user_id' => $userId,
        ])->whereTime('create_time', 'month')
          ->sum('commission');

        return $stats;
    }
} 